package com.link.play.fit.ai.utils

import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import com.link.play.fit.ai.ext.d
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object ScreenshotUtils {
    /**
     * 获取动态截图 的bitmap View
     */
    fun getShotDynamicView(content: View, top: View, bottom: View):Bitmap {
        val h = top.height + content.height + bottom.height
        val bitmap = Bitmap.createBitmap(content.width, h, Bitmap.Config.ARGB_8888)
        "获取控件的宽高 ${content.height}  ${content.width}  ".d()
        val canvas = Canvas(bitmap)
        val topBit = shotView(top)
        val contentBit = shotView(content)
        val bottomBit = shotView(bottom)
        val paint = Paint()
        canvas.drawColor(Color.WHITE)
        canvas.drawBitmap(topBit, 0f, 0f, paint)
        canvas.drawBitmap(contentBit, 0f, top.height.toFloat(), paint)
        canvas.drawBitmap(bottomBit, 0f, h - bottom.height.toFloat(), paint)
        return bitmap
    }
    /**
     * 截取普通view
     */
    fun shotView(view: View): Bitmap {

        view.isDrawingCacheEnabled = true
        view.buildDrawingCache()
//        "再次获取宽高 ${view.width} ${view.drawingCache.width}".e()

        val bitmap = Bitmap.createBitmap(view.drawingCache)
//        val bitmap = view.drawingCache

        view.isDrawingCacheEnabled = false
        return bitmap
    }
    fun captureScreenAndSaveToFile(view: View): File? {
        // 1. 创建 Bitmap
        val bitmap = getScreenBitmap(view) ?: return null

        // 2. 保存到文件
        return try {
            val file = createImageFile() // 创建文件对象
            FileOutputStream(file).use { fos ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos) // 压缩为 JPEG
                fos.flush()
            }
            file
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 获取屏幕 Bitmap（兼容 Android 5.0+）
    private fun getScreenBitmap(view: View): Bitmap? {
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache()
        val bitmap = Bitmap.createBitmap(view.drawingCache)
        view.isDrawingCacheEnabled = false
        return bitmap
    }

    // 创建唯一的图片文件（适配 Android 10+ 作用域存储）
    private fun createImageFile(): File {
        // 文件名带时间戳（避免重复）
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val fileName = "SCREENSHOT_$timestamp.jpg"

        // 保存路径（优先公共目录）
        val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        return File(storageDir, fileName)
    }

    fun saveBitmapToPublicDir(context: Context, bitmap: Bitmap): File? {
        val fileName = "screenshot_${System.currentTimeMillis()}.jpg"
        val resolver = context.contentResolver

        // Android 10+ 使用 MediaStore
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val contentValues = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
            }

            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            uri?.let {
                resolver.openOutputStream(it)?.use { stream ->
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream)
                }
                File(uri.toString()) // 实际应使用 uri 操作文件
            }
        } else {
            // Android 9 及以下：保存到公共目录并申请权限
            val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            if (!storageDir.exists()) storageDir.mkdirs()
            val file = File(storageDir, fileName)
            try {
                FileOutputStream(file).use { stream ->
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream)
                }
                file
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }

    fun getBitmap(context: Activity):Bitmap{
        // 获取当前窗口的 DecorView
        val decorView = context.window.decorView
        decorView.isDrawingCacheEnabled = true
        decorView.buildDrawingCache()
        val bitmap = decorView.drawingCache
        return bitmap
    }
//    fun saveBitmap(context: Context,bitmap: Bitmap){
//        // 保存到应用缓存目录（无需存储权限）
//        val cacheDir = context.externalCacheDir ?: context.cacheDir
//        val file = File(cacheDir, "screenshot_${System.currentTimeMillis()}.png")
//        FileOutputStream(file).use {
//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
//        }
//        val uri = FileProvider.getUriForFile(
//            context,
//            "${context.packageName}.fileprovider",
//            file
//        )
//        val intent = Intent(Intent.ACTION_SEND).apply {
//            type = "image/*"
//            putExtra(Intent.EXTRA_STREAM, uri)
//            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
//        }
//        context.startActivity(Intent.createChooser(intent, "分享截图"))
//    }
}